package com.baitai.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Hex;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.Asserts;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class SigmobUtils {

    /**
     * ToBid Public Key，从聚合平台->账户管理->Keys功能页获取。
     */
    private static final String PUBLIC_KEY = "7d650afaa932cd3ba0a7d4220a7468ac";
    /**
     * ToBid Secret Key，从平台账户管理->Keys功能页获取。
     */
    private static final String SECRET_Key = "3fc8e180f4665a133bea8e42fbe95bb1";

    /**
     * 签名使用 SHA-1(160bit)算法生成<br/>
     *
     * @param plainText
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String sha1(String plainText) throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA");
        byte[] cipherBytes = messageDigest.digest(plainText.getBytes());
        String cipherStr = Hex.encodeHexString(cipherBytes);
        return cipherStr;
    }

    /**
     * 获取 URL 请求的所有参数对，按参数名升序排序后，将所有参数值做字符串连接<br/>
     * 在拼接后的字符串后，再追加secret key，计算出用于签名的字符串<br/>
     *
     * @param requestParams
     * @return
     */
    public static String prepaireSignPlainText(List<NameValuePair> requestParams) {
        // 先对请求参数按照参数名升序排序
        Collections.sort(requestParams, new Comparator<NameValuePair>() {
            @Override
            public int compare(NameValuePair o1, NameValuePair o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        // 将排序后的参数对的value值按次拼成一个字符串
        StringBuilder sb = new StringBuilder();
        requestParams.forEach(temp -> {
            sb.append(temp.getValue());
        });

        /**
         * 注意，这里别忘了追加secretKey
         */
        sb.append(SECRET_Key);
        return sb.toString();
    }

    /**
     * 获取 URL 请求的所有参数对，按参数名升序排序后，将所有参数值做字符串连接。<br/>
     * 在拼接后的字符串后，再追加secret key，计算出用于签名的字符串<br/>
     * 对得到的字符串进行SHA-1(160bit)哈希操作得到的值即为请求签名。<br/>
     *
     * @param requestParams
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String sign(List<NameValuePair> requestParams) throws NoSuchAlgorithmException {
        String plainText = prepaireSignPlainText(requestParams);
        return sha1(plainText);
    }

    /**
     * 将key value对转换成http请求参数对<br/>
     *
     * @param params
     * @return
     */
    public static List<NameValuePair> buildRequestParam(Map<String, String> params) {
        // 将传入的key value对转换成http请求参数
        List<NameValuePair> requestParams = params.entrySet().stream().map(temp -> {
            NameValuePair nvp = new BasicNameValuePair(temp.getKey(), temp.getValue());
            return nvp;
        }).collect(Collectors.toList());

        return requestParams;
    }

    /**
     * @param url    接口地址
     * @param params 接口需要的业务参数对（不包含api_key,timestamp,sign这个三个用于签名校验的参数）
     * @throws IOException
     * @throws URISyntaxException
     * @throws NoSuchAlgorithmException
     */
    public static String getData(String url, Map<String, String> params) {
        String result = null;
        // 根据传入参数，创建http request参数对
        List<NameValuePair> requestParams = buildRequestParam(params);
        // 除了业务需要的请求参数外，需要追加时间戳以及public key参数用于签名验证
        // 服务端会校验时间戳参数 timestamp，请求时间在服务器时间±5s 内请求有效
        NameValuePair timestampNVP = new BasicNameValuePair("timestamp", String.valueOf(System.currentTimeMillis()));
        NameValuePair pkNVP = new BasicNameValuePair("api_key", PUBLIC_KEY);
        requestParams.add(timestampNVP);
        requestParams.add(pkNVP);

        //计算签名
        String signStr = null;
        try {
            signStr = sign(requestParams);

            //别忘了把得到的签名也传给服务端
            NameValuePair signNVP = new BasicNameValuePair("sign", signStr);
            requestParams.add(signNVP);

            URI uri = new URIBuilder(new URI(url)).addParameters(requestParams).build();

            HttpGet httpGet = new HttpGet(uri);

            httpGet.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8");
            HttpClient httpclient = HttpClients.createDefault();

            HttpResponse response = httpclient.execute(httpGet);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                result = resEntity != null ? EntityUtils.toString(resEntity, "utf-8") : "";
            }
            System.out.println("---------result:" + result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {


        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // 设置时间格式
        Date date = DateUtils.yesterdayStart();
        String datestr = formatter.format(date);
        System.out.println(datestr);

//        Asserts.check(!PUBLIC_KEY.isEmpty(), "请填写ToBid Public Key");
//        Asserts.check(!SECRET_Key.isEmpty(), "请填写ToBid Secret Key");
//
//        Map<String, String> params = new HashMap<String, String>();
//        params.put("start_date", "2024-12-21");
//        params.put("end_date", "2024-12-21");
//        params.put("group_by", "placement");
//        params.put("page_size", "1");
//        try {
////            System.out.println(getData("https://report.sigmob.com/pub/mediation/v2/report", params));
//            String resultData = SigmobUtils.getData("https://report.sigmob.com/pub/mediation/v2/report", params);
//            System.out.println("sigmobData:  " + resultData);
//            JSONObject result = JSONObject.parseObject(resultData);
//
//            if (result != null && result.getString("code").equals("200")) {
//                JSONObject dataJS = result.getJSONObject("data");
//                JSONArray listJS = dataJS.getJSONArray("list");
//                for (int i = 0; i < listJS.size(); i++) {
//                    System.out.println(listJS.get(i).toString());
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }
}
